package com.cq.digitalemployee.shiro.redis;

import org.apache.shiro.session.Session;
import org.apache.shiro.session.mgt.eis.EnterpriseCacheSessionDAO;
import org.springframework.data.redis.core.RedisTemplate;

import java.io.Serializable;

/**
 * shiro-redis-session操作类
 *
 * @author zzz
 */
public class ShiroRedisSessionDao extends EnterpriseCacheSessionDAO {

    private RedisTemplate<byte[], byte[]> redisTemplate;

    public ShiroRedisSessionDao(RedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;

    }

    @Override
    protected Serializable doCreate(Session session) {
        Serializable sessionId = super.generateSessionId(session);
        redisTemplate.opsForValue().set(sessionId.toString().getBytes(), SerializeUtil.serialize(session));
        return sessionId;
    }

    @Override
    protected Session doReadSession(Serializable sessionId) {
        Session session = super.doReadSession(sessionId);
        if (session == null) {
            byte[] sessionBytes = redisTemplate.opsForValue().get(sessionId.toString().getBytes());
            if (sessionBytes != null && sessionBytes.length > 0) {
                session = (Session) SerializeUtil.unSerialize(sessionBytes);
            }
        }
        return session;
    }

    @Override
    protected void doUpdate(Session session) {
        super.doUpdate(session);
        redisTemplate.opsForValue().set(session.getId().toString().getBytes(), SerializeUtil.serialize(session));
    }

    @Override
    protected void doDelete(Session session) {
        super.doDelete(session);
        redisTemplate.delete(session.getId().toString().getBytes());
    }

}
